<?php
require('../wp-load.php');

function contest_format_date($input) {
    $d = substr($input, 0, 16);    
    $d = str_replace("-",".", $d);
    
    $darrs = explode(" ", $d);
    $date = $darrs[0];
    $time = $darrs[1];
    $dateArrs = explode(".", $date);
    $dateStr = $dateArrs[2] . "." . $dateArrs[1] . "." . $dateArrs[0];
    return $dateStr . " " . $time;
}

function contest_display_as_number($num, $checknum = 1) {
    if(!$checknum) {
        return "0";
    }
    if($num){
        return $num;
    } else {
        return "0";
    }
}

global $current_user;
// get data from database
$contestID = $_GET['contest_id'];
$smtUserID = $_GET['smt_user_id'];
$result = $wpdb->get_results("
    select * from
    (
    select scd.*, ld.user_like_id, count(*) as num_of_like from 
            (select * from st_contest_data where contest_id = {$contestID}) scd
                left join
            (select * from st_contest_user_like_data where smt_user_id = {$smtUserID}) ld
                on scd.data_id = ld.data_id
            group by scd.data_id
    ) tb1 left join st_contest_user lu
    on tb1.user_id = lu.user_id
    ");
$name = "All contests";
$contestDetail = $wpdb->get_row("select * from  st_contest_contest where contest_id = {$_GET['contest_id']}");
$name = $contestDetail->name;
// export csv
$exportFileName = "detailed-formdata-" . date_i18n('d-m-Y') . "_" . time() . ".csv";

// print list of title
$titleString = "\"name\",\"email\",\"hometown\",\"birthday\"";
$firstRow = $result[0];

require_once 'libs/formbuilder.php';
$formbuilder = new formbuilder();
$rowDataArrs = $formbuilder->getDataArratFromData(json_decode($firstRow->form_data));
$firstRowDataArrForm = $rowDataArrs[0];
foreach($firstRowDataArrForm as $k => $v) {
    $titleString .= ",\"{$k}\"";
}
$contentString = "";

foreach($result as $rk => $rv) {
    $contentString .= "\"{$rv->name}\",\"{$rv->email}\",\"{$rv->hometown}\",\"{$rv->birthday}\"";
    $row = $rv;
    $rowArrs = $formbuilder->getDataArratFromData(json_decode($row->form_data));
    $rowData = $rowArrs[0];
    foreach($rowData as $k1 => $v1) {
        $contentString .= ",\"{$v1}\"";
    }
    $contentString .= "\r\n";
}


header("Content-type:text/octect-stream; charset=utf-8");
header("Content-Disposition:attachment;filename={$exportFileName}");
echo $titleString . "\r\n";
echo $contentString;
//print_r($formArr);die;